import re
from collections import Iterable

from PageObjectRequests import base_url
from util import http_utils
from util.DataQuery.hzflowOperation import hzflowOperation
from util.inform.sendEmail import sendEmail
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.FormDataDecorator import FormDataDecorator

from PageObjectRequests.write_equity import WriteCivilType, WriteLegalType, WriteVentureInvestment

# # # # # # # # # # # # #              填写注册登记表                       3       # # # # # # # #   unfinished----guquanjiegou                 # # # #
from util.g import g
from util.sys_dict import saleIncome, listedType


class WriteRegistrationForm():
    token = ""
    # form_btn_loc = (By.XPATH, '//a[contains(text(), "注册登记表")]')
    form_btn_loc = (By.LINK_TEXT, "注册登记表")
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")

    def __init__(self, driver=None, perfect=False):
        self.driver = driver
        self.perfect = perfect

    def __call__(self, *args, **kwargs):
        print("args", args)
        print("kwargs", kwargs)
    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, esdate="", contact='', contact_phone='', contact_tel='', contact_fax='',contact_email='',legal_phone='', legal_tel='', legal_fax='', legal_email='',dom='', postalcode='', scale='',hitech_field_namelist='', hitech_field_idlist="", gopublic="", stockcat='', gopublictime='', stockcode='',opscope='；', entbrief_intro=''):
        # 获取 注册登记表 查询接口
        try:
            if not self.perfect:
                # 获取 页面用于获取表单参数
                # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
                detail_url = ele.get_attribute("href")
                if not g.all_optimized:
                    # 全部优化完成可以不走这一步
                    BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
            else:
                detail_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/EntInfoChange/initRegDataForUpdate.do"
            BM.get_cookie(driver=self.driver)

            detail_url = detail_url if detail_url.startswith("https://") else \
                base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)

            res = http_utils.send_get(detail_url, driver=self.driver)
            text = res.get("text")
            token = res.get("token")
            self.token = token

            # 注册登记表链接
            url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveRegLoginInfo.do"
            if self.perfect:
                # 基本信息链接
                url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/EntInfoChange/saveRegDataForUpdate.do"
            data = {
                "struts.token.name": "token",
                # 这个 token 需要在页面上获取
                # "token": "A9PP8YY9JH8IUZLV3Q9YZZLO4XFEZV15",
                "token": g.token,
                "userInfo.contName": contact,
                "userInfo.contMobile": contact_phone,
                "userInfo.contTel": contact_tel if contact_tel else "",
                "userInfo.contFax": contact_fax if contact_fax else "",
                "userInfo.contEmail": contact_email,
                "userInfo.corMobile": legal_phone if legal_phone else contact_tel,
                "userInfo.corTel": legal_tel if legal_tel else "",
                "userInfo.corFax": legal_fax if legal_fax else "",
                "userInfo.corEmail": legal_email if legal_email else contact_fax,
                "userInfo.address": dom,
                "userInfo.postalcode": postalcode,
                "userInfo.saleIncome": str(saleIncome.get(scale)),
                # 根据 hitech_field_namelist 获取 国网技术领域对应value
                # gopublic 为 1 时 增加这些数据
                # 这些在另三个 class 中获取数据
                # 这个字段在 注册登记表中有 但在 企业基本信息修改中没有
            }
            # 获取技术领域信息
            domain_dict = hzflowOperation.get_domain_by_namelist(hitech_field_namelist=hitech_field_namelist)
            data["userInfo.mainDomain1"] = domain_dict.get("domain1")
            data["userInfo.mainDomain2"] = domain_dict.get("domain2")
            data["userInfo.mainDomain3"] = domain_dict.get("domain3")
            data.update(domain_dict)
            data["userInfo.marketStatus"] = gopublic
            if gopublic == 1:
                data["userInfo.listedType"] = str(listedType.get(stockcat))
                data["userInfo.marketDate"] = gopublictime
                data["userInfo.marketCode"] = stockcode if stockcode else ""
            # 获取股权结构和风险投资信息
            legal = []
            civilType = WriteCivilType(driver=self.driver).write()

            legal.extend(civilType if isinstance(civilType, Iterable) else [])
            legalType = WriteLegalType(driver=self.driver).write()
            legal.extend(legalType if isinstance(legalType, Iterable) else [])
            ventureInvestment = WriteVentureInvestment(driver=self.driver).write()
            legal.extend(ventureInvestment if isinstance(ventureInvestment, Iterable) else [])
            for i, item in enumerate(legal):
                data["entEquityList[{}].personType".format(i)] = item.get("type")
                data["entEquityList[{}].personName".format(i)] = item.get("name")
                data["entEquityList[{}].idCode".format(i)] = item.get("id_num")
                data["entEquityList[{}].touzi".format(i)] = item.get("invest")
            data["userInfo.operation"] = opscope
            if not self.perfect:
                data["userInfo.companyProfile"] = entbrief_intro
            data["hide"] = ""
            # 从页面中 获取 userInfo.id
            user_info_id_pattern = '.*?<input.*?name="userInfo.id".value="(.*?)".*?'
            id_res = re.findall(user_info_id_pattern, text, re.S)

            # userInfo.id 也需要从页面中获取
            # data["userInfo.id"] = "2020050916115411340"
            data["userInfo.id"] = "".join(id_res)

            result = http_utils.send_post(url, data=data, driver=self.driver)
            text = result.get("text")
            message = result.get("message")
            form_name = "注册登记表"
            if self.perfect:
                form_name = "企业基本信息"
            g.logger.info("{}上传结果: {}".format(form_name, message))
            token = result.get("token")
            self.token = token

            if u"成功" in message:
                # 企业基本信息不修改上传状态
                if not self.perfect:
                    return True
                else:
                    return False
            else:
                content = "{}-{}---{}--{}".format(g.entname, g.co_id, "注册登记表", message)
                a = sendEmail(subject="autoflow", content=content, target="18235693860@163.com")
                a.send_mail()
                return False
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)

